<?php

namespace App\Http\Controllers\Api\Merchant;

use App\BalanceRecord;
use App\Classify;
use App\Enterprise;
use App\EnterpriseAdmin;
use App\Exports\MedicineExport;
use App\Exports\OrdersExport;
use App\Http\Services\MerchantManager;
use App\Merchant;
use App\MerchantMedicine;
use App\MerchantMedicineXClassify;
use App\MerchantStaff;
use App\Message;
use App\OrderItem;
use App\Orders;
use App\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Maatwebsite\Excel\Facades\Excel;

class DataController extends Controller
{
    /**
     * 商家交易流水
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getEnterpriseMoneyChange(Request $request){
        /** @var User $merchantUser */
        $merchantUser = MerchantManager::isLogin($request);
        if(!$merchantUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $enterpriseInfo = MerchantManager::getMerchantInfoByUserId($merchantUser->id);
        if(!$enterpriseInfo)
            return response()->json(['level' => 'error','message' => '商家信息异常']);

        $page       = $request->input('page')       ?? 1;
        $limit      = $request->input('limit')      ?? 16;
        $merchantId = $request->input('merchant_id')?? 0;
        $keyword    = $request->input('keyword')    ?? '';
        $start_time = $request->input('start_time') ?? '';
        $end_time   = $request->input('end_time')   ?? '';

        $pageInfo = [
            'page' => $page,
            'limit' => $limit,
        ];
        $page=$page-1;

        $eid        = EnterpriseAdmin::getEnterpriseId($merchantUser->id);
        if ($eid){

            $data   = Orders::whereIsPay(1)
                ->whereEnterpriseId($eid);
        } else {

            $mIds = MerchantStaff::whereUserId($merchantUser->id)
                ->pluck('merchant_id')
                ->toArray();

            $data = Orders::whereIsPay(1)
                ->whereIn('merchant_id',$mIds);

        }
        if ($merchantId){
            $data=$data->whereMerchantId($merchantId);
        }
        if ($keyword){
            $data=$data->where('order_num','like','%'.trim($keyword).'%');
        }
        if ($start_time){
            $data=$data->where('created_at','>=',$start_time);
        }
        if ($end_time){
            $data=$data->where('created_at','<',$end_time);
        }
        $pageInfo['total']=$data->count();
        $data=$data->offset($page * $limit)->limit($limit)->get();
        if (count($data) > 0){
            foreach ($data as $item){
                $item->merchant_name=Merchant::getMerchantName($item->merchant_id);
                $item->money_type   =$item->status == 6 ? '订单退款' : '订单收入';
            }
        }
        return response()->json(['level'=>'success','message'=>'success','data'=>$data,'page_info'=>$pageInfo]);
    }

    /**
     * 商家数据统计
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getEnterpriseDataSummary(Request $request){
        /** @var User $merchantUser */
        $merchantUser = MerchantManager::isLogin($request);
        if(!$merchantUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $enterpriseInfo = MerchantManager::getMerchantInfoByUserId($merchantUser->id);
        if(!$enterpriseInfo)
            return response()->json(['level' => 'error','message' => '商家信息异常']);
        $data=[];

        $start_time = date('Y-m-d 00:00:00',time());
        $end_time   = date('Y-m-d 23:59:59',time());

        $data['merchant_num']   = Merchant::whereEnterpriseId($enterpriseInfo->id)->count();
//        $data['enterprise_num'] = Enterprise::count();
        $data['medicine_num']   = MerchantMedicine::whereIsShop(1)
            ->whereIn('merchant_id', Enterprise::getEnterpriseMerchantIds($enterpriseInfo->id))
            ->count();
        $data['today_sum_money']= Orders::whereEnterpriseId($enterpriseInfo->id)
            ->whereBetween('pay_time',[$start_time,$end_time])
            ->whereIsPay(1)
            ->sum('pay_amount');
        $data['today_sum_order_num']= Orders::whereEnterpriseId($enterpriseInfo->id)
            ->whereBetween('pay_time',[$start_time,$end_time])
            ->count();
        $data['user_num']= User::whereEnterpriseId($enterpriseInfo->id)
            ->whereRole(0)
            ->count();
        return response()->json(['level'=>'success','message'=>'success','data'=>$data]);
    }

    /**
     * 商品类型销售情况
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getClassifySelling(Request $request){
        /** @var User $merchantUser */
        $merchantUser = MerchantManager::isLogin($request);
        if(!$merchantUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $data=[];
        $result=[];
        $total=0;
        $start_time = $request->input('start_time') ?? date('Y-m-d 00:00:00',time()-7*24*3600);
        $end_time   = $request->input('end_time')   ?? date('Y-m-d 23:59:59',time());
        $time_info  =[
            'start_time'=>$start_time,
            'end_time'  =>$end_time
        ];

        $eid        = EnterpriseAdmin::getEnterpriseId($merchantUser->id);
        if ($eid){

            $fatherClassifyArr = Classify::whereEnterpriseId($eid)
                ->wherePid(0)
                ->whereType('selling')
                ->get();
            $payOrderId     =Orders::whereIsPay(1)
                ->whereBetween('created_at',[$start_time,$end_time])
                ->whereEnterpriseId($eid)
                ->pluck('id')
                ->toArray();
        } else {

            $mIds = MerchantStaff::whereUserId($merchantUser->id)
                ->pluck('merchant_id')
                ->toArray();

            $payOrderId     =Orders::whereIsPay(1)
                ->whereBetween('created_at',[$start_time,$end_time])
                ->whereIn('merchant_id',$mIds)
                ->pluck('id')
                ->toArray();

            $fatherClassifyArr= Classify::wherePid(0)
                ->whereIn('merchant_id',$mIds)
                ->get();
        }

        if (count($fatherClassifyArr) > 0){
            foreach ($fatherClassifyArr as $classify){
                $allSCIds=Classify::getAllSonClassifyIds($classify->id);
                $thisSCMIds=MerchantMedicineXClassify::whereIn('classify_id',$allSCIds)
                    ->pluck('merchant_medicine_id')
                    ->toArray();

                $sellingNum=OrderItem::whereIn('merchant_medicine_id',$thisSCMIds)
                    ->whereIn('order_id',$payOrderId)
                    ->sum('num');
                $total=$total+$sellingNum;
                $result[$classify->name]=$sellingNum;
            }
            foreach ($result as $key=>$value){
                $temp=[
                    'classify_name'=>$key,
                    'selling_num'=>$value,
                    'percentage'=>$total ? round($value/$total*100,2).'%' : '0%'
                ];
                array_push($data,$temp);
            }
        }
//        $data['total']=$total;
        return response()->json(['level'=>'success','message'=>'success','data'=>$data,'total_selling_num'=>$total,'time_info'=>$time_info]);

    }

    /**
     * 门店营收排行榜
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getMerchantSelling(Request $request){
        /** @var User $merchantUser */
        $merchantUser = MerchantManager::isLogin($request);
        if(!$merchantUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $data=[];
        $total=0;
        $start_time = $request->input('start_time') ?? date('Y-m-d 00:00:00',time()-7*24*3600);
        $end_time   = $request->input('end_time')   ?? date('Y-m-d 23:59:59',time());
        $time_info  =[
            'start_time'=>$start_time,
            'end_time'  =>$end_time
        ];

        $eid        = EnterpriseAdmin::getEnterpriseId($merchantUser->id);
        if ($eid){
            $merchants=Merchant::whereEnterpriseId($eid)->get();

        } else {

            $mIds = MerchantStaff::whereUserId($merchantUser->id)
                ->pluck('merchant_id')
                ->toArray();
            $merchants=Merchant::whereIn('id',$mIds)->get();
        }
        if (count($merchants) > 0){
            foreach ($merchants as $merchant){
                $payOrderAmount=Orders::whereIsPay(1)
                    ->whereBetween('created_at',[$start_time,$end_time])
                    ->whereMerchantId($merchant->id)
                    ->sum('pay_amount');
                $total=$total+$payOrderAmount;
                $temp=[
                    'amount'=>$payOrderAmount,
                    'merchant_id'=>$merchant->id,
                    'merchant_name'=>$merchant->name
                ];
                array_push($data,$temp);
            }
            arsort($data);
        }
        return response()->json([
            'level'=>'success',
            'message'=>'success',
            'data'=>$data,
            'total_selling_amount'=>$total,
            'time_info'=>$time_info]);
    }

    /**
     * 复购率
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getReBuyRate(Request $request){
        /** @var User $merchantUser */
        $merchantUser = MerchantManager::isLogin($request);
        if(!$merchantUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);
//        $merchantUser=(object)['id'=>65];
        $data=[
            'times_2'=>0,
            'times_3'=>0,
            'times_4'=>0,
            'times_5'=>0,
        ];
        $return=[];
        $total=0;
        $start_time = $request->input('start_time') ?? date('Y-m-d 00:00:00',time()-7*24*3600);
        $end_time   = $request->input('end_time')   ?? date('Y-m-d 23:59:59',time());
        $time_info  =[
            'start_time'=>$start_time,
            'end_time'  =>$end_time
        ];

//        dump($merchantUser->id);die();
        $eid        = EnterpriseAdmin::getEnterpriseId($merchantUser->id);
        if ($eid){
            $merchants=Merchant::whereEnterpriseId($eid)->pluck('id')->toArray();
//            dump($eid);die('sid');
        } else {

            $mIds = MerchantStaff::whereUserId($merchantUser->id)
                ->pluck('merchant_id')
                ->toArray();
            $merchants=Merchant::whereIn('id',$mIds)->pluck('id')->toArray();
        }
//        dump($merchants);die();
        if (count($merchants) > 0){

            $allBuyUsers=Orders::whereIsPay(1)
                ->whereBetween('created_at',[$start_time,$end_time])
                ->whereIn('merchant_id',$merchants)
                ->pluck('user_id')
                ->toArray();
//            dump($allBuyUsers);die();

            if (count($allBuyUsers) > 0){
                //$allBuyUsers=['user_id']

                  $temp=array_count_values($allBuyUsers);
                //$temp=[user_id=>times]
//                dump($temp);die();

                  $result=array_count_values($temp);
                //$result=['times'=>'count']
//                dump($result);die();
                if (count($result) > 0){
                    foreach ($result as $times=>$count){
                        if ($times<5){
                            if ($times>1){
                                $key='times_'.$times;
                                $data[$key]+=$count;
                            }

                        } else {
                            $data['times_5']+=$count;
                        }
                        if ($times>1)
                            $total+=$count;
                    }
                    foreach ($data as $times=>$count){
                        $temp=[
                            $times=>$count,
                            'percentage'=>$total ? round($count/$total*100,2).'%' : '0%'
                        ];
                        array_push($return,$temp);
                    }
                }
            }
        }
        return response()->json(['level'=>'success','message'=>'success','data'=>$return,'time_info'=>$time_info]);
    }

    /**
     * 全天订单量统计
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getOrderCounts(Request $request){
        /** @var User $merchantUser */
        $merchantUser = MerchantManager::isLogin($request);
        if(!$merchantUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $data=[];
        $total=0;
        $start_time = $request->input('start_time') ?? date('Y-m-d 00:00:00',time()-7*24*3600);
        $end_time   = $request->input('end_time')   ?? date('Y-m-d 23:59:59',time());
        $time_info  =[
            'start_time'=>$start_time,
            'end_time'  =>$end_time
        ];

        $eid        = EnterpriseAdmin::getEnterpriseId($merchantUser->id);
        if ($eid){
            $merchants=Merchant::whereEnterpriseId($eid)->get();

        } else {

            $mIds = MerchantStaff::whereUserId($merchantUser->id)
                ->pluck('merchant_id')
                ->toArray();
            $merchants=Merchant::whereIn('id',$mIds)->get();
        }
        if (count($merchants) > 0) {

            $allOrders = Orders::whereIsPay(1)
                ->whereBetween('created_at', [$start_time, $end_time])
                ->whereIn('merchant_id', $merchants)
                ->get();
            if (count($allOrders) > 0){
                foreach ($allOrders as $order){
                    $order_time=strtotime($order->created_at);
                    $order_date=date('Y/m/d',$order_time);
                    if (isset($data[$order_date])){
                        $data[$order_date]+=1;
                    } else {
                        $data[$order_date]=1;
                    }
                }
            }
        }

        return response()->json(['level'=>'success','message'=>'success','data'=>$data,'time_info'=>$time_info]);
    }

    public function enterpriseMoneyExport(Request $request){
        /** @var User $merchantUser */
        $merchantUser = MerchantManager::isLogin($request);
        if(!$merchantUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $enterpriseInfo = MerchantManager::getMerchantInfoByUserId($merchantUser->id);
        if(!$enterpriseInfo)
            return response()->json(['level' => 'error','message' => '商家信息异常']);

        $merchantId = $request->input('merchant_id')?? 0;
        $keyword    = $request->input('keyword')    ?? '';
        $start_time = $request->input('start_time') ?? '';
        $end_time   = $request->input('end_time')   ?? '';

        $fileName ='财务导出-'.$start_time.'至'.$end_time.'--'.rand(1000,9999).'.xlsx';

        $eid        = EnterpriseAdmin::getEnterpriseId($merchantUser->id);
        if ($eid){

            $orderList   = Orders::whereIsPay(1)
                ->whereEnterpriseId($eid);
        } else {

            $mIds = MerchantStaff::whereUserId($merchantUser->id)
                ->pluck('merchant_id')
                ->toArray();

            $orderList = Orders::whereIsPay(1)
                ->whereIn('merchant_id',$mIds);

        }
        if ($merchantId){
            $orderList=$orderList->whereMerchantId($merchantId);
        }
        if ($keyword){
            $orderList=$orderList->where('order_num','like','%'.trim($keyword).'%');
        }
        if ($start_time){
            $orderList=$orderList->where('created_at','>=',$start_time);
        }
        if ($end_time){
            $orderList=$orderList->where('created_at','<',$end_time);
        }
        $pageInfo['total']=$orderList->count();
        $orderList=$orderList->orderByDesc('id')->pluck('id')->toArray();

        $export = new OrdersExport($orderList);

        return Excel::download($export, $fileName);
    }

    public function getUnreadNum(Request $request){
        /** @var User $merchantUser */
        $merchantUser = MerchantManager::isLogin($request);
        if(!$merchantUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $enterpriseInfo = MerchantManager::getMerchantInfoByUserId($merchantUser->id);
        if(!$enterpriseInfo)
            return response()->json(['level' => 'error','message' => '商家信息异常']);

        $messageNum = Message::whereEnterpriseId($enterpriseInfo->id)->whereIsRead(0)->count();

        return response()->json(['level' => 'success','message' => '获取成功','data' => $messageNum]);
    }

    /**
     * 消息列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getMessageList(Request $request){
        /** @var User $merchantUser */
        $merchantUser = MerchantManager::isLogin($request);
        if(!$merchantUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $enterpriseInfo = MerchantManager::getMerchantInfoByUserId($merchantUser->id);
        if(!$enterpriseInfo)
            return response()->json(['level' => 'error','message' => '商家信息异常']);

        $page       = $request->input('page')       ?? 1;
        $limit      = $request->input('limit')      ?? 16;
        $isRead     = $request->input('is_read');

        $pageInfo = [
            'page' => $page,
            'limit' => $limit,
        ];

        $page = $page - 1;

        $messageList = Message::whereEnterpriseId($enterpriseInfo->id);

        if(is_numeric($isRead)){
            $messageList->whereIsRead($isRead);
        }

        $pageInfo['total'] = $messageList->count();

        $messageList = $messageList->orderByDesc('id')->offset($page * $limit)->limit($limit)->get();
        if(count($messageList) > 0){
            foreach ($messageList as $message) {
                $message->merchant_name = Merchant::getMerchantName($message->merchant_id);

                $deliveryMethodName = '';
                $message->order_id = 0;
                $order = Orders::whereOrderNum($message->order_num)->first();
                if($order){
                    $deliveryMethodName = Merchant::getDeliveryName($order->delivery_method);
                    $message->order_id = $order->id;
                }

                $message->delivery_method_name = $deliveryMethodName;
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $messageList,'page_info' => $pageInfo]);
    }

    public function setMessageAlreadyRead(Request $request){
        /** @var User $merchantUser */
        $merchantUser = MerchantManager::isLogin($request);
        if(!$merchantUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $enterpriseInfo = MerchantManager::getMerchantInfoByUserId($merchantUser->id);
        if(!$enterpriseInfo)
            return response()->json(['level' => 'error','message' => '商家信息异常']);

        $id = $request->get('id') ?? 0;

        if($id){
            $message = Message::whereEnterpriseId($enterpriseInfo->id)->whereId($id)->whereIsRead(0)->first();
            if($message){
                $message->is_read = 1;
                $message->save();
            }
        }else{
            $messageList = Message::whereEnterpriseId($enterpriseInfo->id)->whereIsRead(0)->get();
            if(count($messageList) > 0){
                foreach ($messageList as $message) {
                    $message->is_read = 1;
                    $message->save();
                }
            }
        }

        return response()->json(['level' => 'success','message' => '设置成功']);
    }

    public function exportMedicine(Request $request){
        /** @var User $merchantUser */
        $merchantUser = MerchantManager::isLogin($request);
        if(!$merchantUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $enterpriseInfo = MerchantManager::getMerchantInfoByUserId($merchantUser->id);
        if(!$enterpriseInfo)
            return response()->json(['level' => 'error','message' => '商家信息异常']);

        $col = $request->input('col');
        $page       = $request->input('page',1);
        $limit      = $request->input('limit',16);
        $merchantId = $request->input('merchant_id') ?? 0;
        $isShop     = $request->input('is_shop') ?? '';
        $classifyId = $request->input('classify_id');
        $keyword    = $request->input('keyword') ?? '';
        if (!is_array($col)){
            return response()->json(['level'=>'error','message'=>'参数错误']);
        }

        if($merchantUser->role == 3){
            $merchantStaff = MerchantStaff::whereUserId($merchantUser->id)->first();
            if($merchantStaff){
                $merchantId = $merchantStaff->merchant_id;
            }
        }
        $data = [];
        //TODO 查出数据
        /** @var MerchantMedicine $goodsList */
        $goodsList = MerchantMedicine::whereIn('merchant_id',$enterpriseInfo->merchant_id_arr);
        if($merchantId != 0){
            $goodsList = $goodsList->whereMerchantId($merchantId);
        }
        if($keyword != ''){
            $goodsList = $goodsList->where('upc','like','%'.trim($keyword).'%')->orWhere('name','like','%'.trim($keyword).'%');
        }
        if($isShop !== ''){
            $goodsList = $goodsList->whereIsShop($isShop);
        }
        if($merchantId != 0){
            $goodsList = $goodsList->whereMerchantId($merchantId);
        }
        if(is_numeric($classifyId)){
            if($classifyId == 0){
                $classifyIds = Classify::whereEnterpriseId($enterpriseInfo->id)->pluck('id')->toArray();
                $merchantMedicineIds = MerchantMedicineXClassify::whereIn('classify_id',$classifyIds)->pluck('merchant_medicine_id')->toArray();
                $goodsList = $goodsList->whereNotIn('id',$merchantMedicineIds);
            }else{
                $merchantMedicineIds = MerchantMedicineXClassify::whereClassifyId($classifyId)->pluck('merchant_medicine_id')->toArray();
                $goodsList = $goodsList->whereIn('id',$merchantMedicineIds);
            }
        }
        $goodsList = $goodsList->whereIn('merchant_id',$enterpriseInfo->merchant_id_arr);

        try {
            $merchant_name  = [];
            $medicine_data  = $goodsList->get($col);
            $col_head       = [];
            $col_name       = [];
            foreach ($col as $item){
                //同步表头
                if ($item == 'merchant_id'){
//                    array_push($col_head,$item);
                    array_push($col_head,'merchant_name');
//                    array_push($col_name,'门店id');
                    array_push($col_name,'门店名称');
                } elseif ($item == 'drug_type') {
                    array_push($col_head,$item);
//                    array_push($col_head,'drug_name');
//                    array_push($col_name,'药品类型id');
                    array_push($col_name,'药品类型');
                }elseif ($item == 'goods_type') {
                    array_push($col_head,$item);
//                    array_push($col_head,'goods_name');
//                    array_push($col_name,'药品类型id');
                    array_push($col_name,'商品类型');
                } else {
                    array_push($col_head,$item);
                    array_push($col_name,Merchant::getColName($item));
                }
            }
            array_push($data,$col_head);
            array_push($data,$col_name);
            foreach ($medicine_data as $item){
//                $temp = $item->toArray();
                if (isset($item->upc))
                    $item->upc = $item->upc."\t";
                if (isset($item->stock))
                    $item->stock = ($item->stock > 0 ? $item->stock : 0)."\t";
                if (isset($item->selling_price))
                    $item->selling_price = ($item->selling_price > 0 ? $item->selling_price : 0)."\t";
//                    $temp['upc'] = $temp['upc']."\t";
                $tmp_col = [];
                foreach ($col_head as $value){
                    //同步表数据
                    if ($value == 'merchant_name'){
                        if (isset($merchant_name[md5($item->merchant_id)])){
                            $shop_name = $merchant_name[md5($item->merchant_id)];
                        } else {
                            $tmp = Merchant::whereId($item->merchant_id)->first();
                            $shop_name = $tmp ? $tmp->name : '门店不存在';
                            $merchant_name[md5($item->merchant_id)]=$shop_name;
                        }
                        array_push($tmp_col,$shop_name);
                    } else if ($value == 'drug_type'){
                        array_push($tmp_col, MerchantMedicine::getDrugTypeName($item->$value));
                    }else if ($value == 'goods_type'){
                        array_push($tmp_col, MerchantMedicine::getGoodsTypeName($item->$value));
                    } else if ($value == 'is_shop'){
                        array_push($tmp_col,MerchantMedicine::getIsShopName($item->$value));
                    } else {
                        array_push($tmp_col,$item->$value);
                    }
                }
//                $temp = array_values($temp);
//                array_push($data,$temp);
                array_push($data,$tmp_col);
            }
            $filePath = 'excel/'.'excel_export_temp/';
            $fileName ='medicine-'.date('ymd-his').rand(10000,99999).'.xlsx';
            $export = new MedicineExport($data);
            Excel::store($export, $filePath.$fileName,'oss','Xlsx');
        } catch (\Exception $e){
            \Log::error('exportMedicine()=>'.$e->getMessage());
            \Log::error('exportMedicine()Trace=>'.$e->getTraceAsString());
            return response()->json(['level'=>'error','message'=>'发生错误：'.$e->getMessage()]);
        }
        return response()->json(['level'=>'success','message'=>'success','data'=>env('OSS_FILE_URL').'/'.$filePath.$fileName]);

    }

    /**
     * 获取充值记录
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getBalanceRecordList(Request $request) {
        /** @var User $merchantUser */
        $merchantUser = MerchantManager::isLogin($request);
        if(!$merchantUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $enterpriseInfo = MerchantManager::getMerchantInfoByUserId($merchantUser->id);
        if (!$enterpriseInfo)
            return response()->json(['level' => 'error','message' => '商家信息异常']);

        $page = $request->input('page') ?? 1;
        $limit = $request->input('limit') ?? 10;

        $pageInfo = [
            'page' => $page,
            'limit' => $limit
        ];

        $page = $page - 1;

        $balanceRecordList = BalanceRecord::where('id', '>', 0);

        $pageInfo['total'] = $balanceRecordList->count();

        $balanceRecordList = $balanceRecordList->offset($page * $limit)->limit($limit)->orderByDesc('created_at')->get();

        if (count($balanceRecordList) > 0) {
            foreach ($balanceRecordList as $balanceRecord) {

                $balanceRecord->type_name = $balanceRecord->type == 0 ? '充值' : '';

                $balanceRecord->is_pay_name = $balanceRecord->is_pay == 1 ? '已支付' : '未支付';

                $balanceRecord->status_name = $balanceRecord->status == 1 ? '已完成' : '未完成';

                $balanceRecord->pay_way_name = $balanceRecord->pay_way == 'wechatpay' ? '微信支付' : '';
            }
        }

        return response()->json(['level' => 'success', 'message' => '获取成功', 'data' => $balanceRecordList]);
    }
}
